package com.zf.powerjob.worker.processor.cron_init;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zf.powerjob.worker.constants.BasicConstants;
import com.zf.powerjob.worker.entity.JobInfo;
import com.zf.powerjob.worker.entity.WorkflowInfo;
import com.zf.powerjob.worker.mapper.JobInfoMapper;
import com.zf.powerjob.worker.mapper.WorkflowInfoMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import tech.powerjob.common.enums.TimeExpressionType;
import tech.powerjob.worker.core.processor.ProcessResult;
import tech.powerjob.worker.core.processor.TaskContext;
import tech.powerjob.worker.core.processor.sdk.BasicProcessor;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 重置并关闭定时任务和工作流
 */
@Component
@Slf4j
public class ResetAndStopCronProcessor implements BasicProcessor {

    @Resource
    private WorkflowInfoMapper workflowInfoMapper;
    @Resource
    private JobInfoMapper jobInfoMapper;

    @Override
    public ProcessResult process(TaskContext context) throws Exception {
        String params = context.getInstanceParams();
        if (StringUtils.isBlank(params)) {
            params = context.getJobParams();
        }
        if (StringUtils.isNotBlank(params) && !JSON.isValid(params)) {
            return new ProcessResult(false, "参数格式错误，正确格式：{\"workflow\": \"cron_1,cron_2\", \"job\": \"cron_1,cron_2\"}");
        }
        JSONObject jsonObject = JSONObject.parseObject(params);
        String workflowParam = Optional.ofNullable(jsonObject.getString(BasicConstants.WORKFLOW_KEY)).orElse("");
        String jobParam = Optional.ofNullable(jsonObject.getString(BasicConstants.JOB_KEY)).orElse("");

        // 分割参数
        List<String> workflowExtraList = Arrays.stream(StringUtils.split(workflowParam, ","))
                .map(StringUtils::trim)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        List<String> jobExtraList = Arrays.stream(StringUtils.split(jobParam, ","))
                .map(StringUtils::trim)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());

        // 查询cron类型的job和工作流
        List<JobInfo> cronJobList = jobInfoMapper.getCronJobs(jobExtraList);
        List<WorkflowInfo> cronWorkflowList = workflowInfoMapper.getCronWorkflows(workflowExtraList);

        // 关闭定时任务
        for (JobInfo job : cronJobList) {
            job.setNextTriggerTime(null);
            job.setTimeExpressionType(TimeExpressionType.API.getV());
        }
        // 关闭工作流
        for (WorkflowInfo workflow : cronWorkflowList) {
            workflow.setNextTriggerTime(null);
            workflow.setTimeExpressionType(TimeExpressionType.API.getV());
        }

        // 更新到数据库
        for (JobInfo job : cronJobList) {
            jobInfoMapper.updateById(job);
        }
        for (WorkflowInfo workflow : cronWorkflowList) {
            workflowInfoMapper.updateById(workflow);
        }
        return new ProcessResult(true);
    }
}
